package com.ledim.utils;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.TextView;
import com.ledim.app.LeDimApplication;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * LedimBaseUtils
 *
 * @author ccx
 */
public class LedimBaseUtils {

    private static int screenWidth = 0;
    private static int screenHeight = 0;

    /**
     * 将 数值字符串转换为int
     *
     * @param str
     *         数值字符串，可以是int或者double的数值
     * @return
     */
    public static int stringToInt(String str) {
        if (isEmpty(str)) {
            return 0;
        } else {
            // return Integer.parseInt(str);
            return (int) Double.parseDouble(str);
        }

    }

    /**
     * 对数值字符串取整
     *
     * @param str
     * @return
     */
    public static String stringToIntStr(String str) {
        return String.valueOf(stringToInt(str));
    }

    /**
     * 判断数据是否为""或null或0
     *
     * @param str
     * @return
     */
    public static boolean isNullity(String str) {
        return (isEmpty(str) || TextUtils.equals(str, "0"));
    }

    /**
     * 判断字符串是否为空
     *
     * @param text
     *         文字
     * @return
     */
    public static boolean isEmpty(String text) {
        return TextUtils.isEmpty(text);
    }

    public static boolean isNotEmpty(String text) {
        return !isEmpty(text);
    }

    /**
     * 修正字符串
     *
     * @param text
     *         文字
     * @return
     */
    public static String trim(String text) {
        return isEmpty(text) ? "" : text.trim();
    }

    public static String trimHtmlStr(String htmlStr) {
        try {
            Spanned spanned = Html.fromHtml(LedimBaseUtils.trim(htmlStr));
            if (spanned != null) {
                return spanned.toString();
            } else {
                return trim(htmlStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return trim(htmlStr);
        }
    }

    /**
     * 修正详情字符串
     *
     * @param text
     *         文字
     * @return
     */
    public static String trimHouseDetail(String text) {
        return isEmpty(text) ? "--" : text.trim();
    }

    /**
     * 修正详情数字为字符串
     *
     * @param number
     *         数字
     * @return
     */
    public static String trimHouseDetail(double number) {
        return number > 0 ? number + "" : "--";
    }

    /**
     * 修正详情数字为字符串
     *
     * @param number
     *         数字
     * @return
     */
    public static String trimHouseDetail(int number) {
        return number > 0 ? number + "" : "--";
    }

    public static String trimDash(String tele) {
        return trim(tele).contains("-") ? trim(tele).replace("-", "") : trim(tele);
    }

    /**
     * 去掉小数点后面的数字
     *
     * @param string
     * @return
     */
    public static String trimPointer(String number) {
        if (null == number || 0 >= number.length()) {
            return "";
        }

        return (trim(number).split("\\."))[0];
    }

    /**
     * 保留小数点后n位
     *
     * @param string
     * @return
     */
    public static String trimPointerN(String number, int n) {
        if (null == number || 0 >= number.length() || 0 > n) {
            return number;
        }

        String lastStr = "";
        String[] array = trim(number).split("\\.");

        if (array.length > 1 && array[1].length() > 0) { // 可能小数位数不够n的个数
            int end = Math.min(n, array[1].length());
            lastStr = array[1].substring(0, end);
        } else if (array.length == 1) {
            lastStr = "0";
        } else {
            return "";
        }

        return array[0] + "." + lastStr;
    }

    /**
     * 获取替换字符串
     *
     * @param data
     *         字符串原型
     * @param args
     *         要替换的参数
     * @return 替换后的字符串
     */
    public static Spanned getReleaseString(String data, Object[] args) {
        String s = String.format(data, args);
        Spanned span = Html.fromHtml(s);
        return span;
    }

    /**
     * 替换字符串某一段的颜色
     *
     * @param data
     *         数据源
     * @param color
     *         要替换成的颜色
     * @param index
     *         开始下标
     * @param length
     *         要替换的长度
     * @return 替换后的字符串
     */
    public static SpannableString getReleaseColorString(String data, int color, int index,
                                                        int length) {
        SpannableString ss = new SpannableString(data);
        ss.setSpan(new ForegroundColorSpan(color), index, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return ss;
    }

    /**
     * 判断输入的电话号码格式是否正确
     *
     * @param phoneNumber
     *         字符串
     * @return
     */
    public static boolean accountNumberIsTrue(String phoneNumber) {
        String regex = "^1[3|4|5|8]\\d{9}$";
        boolean result = phoneNumber.matches(regex);
        return result;
    }

    /**
     * 判断输入的电话号码格式是否正确
     *
     * @param phoneNumber
     *         字符串
     * @return
     */
    public static boolean newhouseNumberIsTrue(String phoneNumber) {
        return phoneNumber.startsWith("1") && phoneNumber.length() == 11;
    }

    /**
     * 是否是手机号
     *
     * @param phoneNum
     * @return
     */
    public static boolean isMobileNumber(String phoneNum) {
        if (phoneNum != null) {
            /*
             * return phoneNum .matches(
			 * "^((13[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(14[0-9]))\\d{8}$");
			 */
            return phoneNum.matches("^\\d{11}$");
        } else {
            return false;
        }
    }

    /**
     * 手机号验证
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isMobile(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p =
                Pattern.compile("^0?(13[0-9]|15[012356789]|18[012356789]|14[57]|17[0678])[0-9]{8}"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
    }

    /**
     * 获取用户手机号码
     *
     * @param context
     *         上下文
     * @return
     */
    public static String getUserPhoneNumber(Context context) {
        TelephonyManager telephonyManager =
                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String phoneNumber = telephonyManager.getLine1Number();
        if (!LedimBaseUtils.isEmpty(phoneNumber) && phoneNumber.length() > 11) {
            phoneNumber = phoneNumber.substring(phoneNumber.length() - 11, phoneNumber.length());
        }
        return phoneNumber;
    }

    /**
     * 判断是否连接GPS
     *
     * @param context
     *         上下文
     * @return
     */
    public static boolean isOpenGps(Context context) {
        LocationManager locationManager =
                (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    /**
     * 判断是否连接网络
     *
     * @param context
     *         上下文
     * @return 是否连接网络
     */
    public static boolean isConnectNet(Context context) {
        ConnectivityManager conManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conManager == null) {
            return false;
        } else {
            NetworkInfo[] info = conManager.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].isConnected()) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 是否存在SDCard
     *
     * @return
     */
    public static boolean isHasSDCard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 字符串是否是数字组成
     *
     * @param str
     *         字符串
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 通过Url解析文件名字
     *
     * @param imageUrl
     *         图片uri
     * @return 文件名字
     */
    public static String parserImageName(String imageUrl) {
        try {
            return imageUrl.substring(imageUrl.lastIndexOf("/") + 1, imageUrl.lastIndexOf("."));
        } catch (Exception e) {
            e.printStackTrace();
            return imageUrl;
        }
    }

    /**
     * 格式化文件大小
     *
     * @param context
     *         上下文
     * @param length
     *         长度
     * @return
     */
    public static String formatFileSize(Context context, long length) {
        return Formatter.formatFileSize(context, length);
    }

    /**
     * 获取图片库中选择图片的地址
     *
     * @param context
     *         上下文
     * @param data
     *         Intent对象
     * @return 图片地址
     */
    @SuppressLint("NewApi")
    public static String getPicPathFormLibs(Context context, Intent data) {
        if (data != null) {
            Uri uri = data.getData();
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                if (!DocumentsContract.isDocumentUri(context, uri)) {
                    return getFilePathForUri(context, uri, null, null);
                }
                String id = DocumentsContract.getDocumentId(uri).split(":")[1];
                String selection = MediaColumns._ID + "=?";
                String[] selectionArgs = new String[] { id };
                return getFilePathForUri(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
            } else {
                return getFilePathForUri(context, uri, null, null);
            }
        }
        return null;
    }

    /**
     * 根据uri获取文件路径
     *
     * @param context
     * @param uri
     * @param selection
     * @param selectionArgs
     * @return
     */
    public static String getFilePathForUri(Context context, Uri uri, String selection,
                                           String[] selectionArgs) {
        String filePath = null;
        String[] filePathColumns = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver()
                               .query(uri, filePathColumns, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumns[0]);
            filePath = cursor.getString(columnIndex);
            cursor.close();
        }
        return filePath;
    }

    /**
     * 输入流转化成字节数组
     *
     * @param is
     * @return
     */
    public static byte[] streamToBytes(InputStream is) {
        byte[] b = null;
        ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = is.read(buffer)) >= 0) {
                os.write(buffer, 0, len);
            }
            b = os.toByteArray();
            os.flush();
            os.close();
            is.close();
        } catch (java.io.IOException e) {
            e.printStackTrace();
            return null;
        }
        return b;
    }

    @SuppressWarnings("deprecation")
    public static String getForegroundActivityName(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        return am.getRunningTasks(100).get(0).topActivity.getShortClassName();
    }

    /**
     * 获取网络类型
     *
     * @param context
     * @return
     */
    public static String getNetType(Context context) {
        String netType = "其他";
        ConnectivityManager connMgr =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                netType = "WIFI";
            } else {
                TelephonyManager telmng =
                        (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                if (telmng.getDataState() == TelephonyManager.DATA_CONNECTED) {
                    switch (telmng.getNetworkType()) {
                        case TelephonyManager.NETWORK_TYPE_GPRS:
                        case TelephonyManager.NETWORK_TYPE_EDGE:
                        case TelephonyManager.NETWORK_TYPE_CDMA:
                            netType = "2G";
                            break;
                        case TelephonyManager.NETWORK_TYPE_EVDO_0:
                        case TelephonyManager.NETWORK_TYPE_EVDO_A:
                        case TelephonyManager.NETWORK_TYPE_EVDO_B:
                        case TelephonyManager.NETWORK_TYPE_UMTS:
                        case TelephonyManager.NETWORK_TYPE_HSDPA:
                        case TelephonyManager.NETWORK_TYPE_HSPA:
                            netType = "3G";
                            break;
                        case TelephonyManager.NETWORK_TYPE_LTE:
                            netType = "4G";
                            break;
                    }
                }

            }
        }

        return netType;
    }

    /**
     * 把list转为字符串
     *
     * @param list
     * @return
     */
    public static String transferListToString(List<String> list) {
        if (list != null && list.size() > 0) {
            StringBuffer sb = new StringBuffer();
            for (String str : list) {
                sb.append(str).append(",");
            }
            return sb.toString().substring(0, sb.length() - 1);
        }
        return null;
    }

    public static List<String> transferStringToList(String str) {
        if (isEmpty(str)) {
            return null;
        }
        return new ArrayList<String>(Arrays.asList(str.split(",")));
    }

    /**
     * 在View未绘制之前测量其宽度
     *
     * @param v
     */
    public static int getWidth(View v) {
        int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        v.measure(width, height);
        return v.getMeasuredWidth();
    }

    /**
     * 在View未绘制之前测量其高度
     *
     * @param v
     */
    public static int getHeight(View v) {
        int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        v.measure(width, height);
        return v.getMeasuredHeight();
    }

    /**
     * 把String转为Integer
     *
     * @param numText
     * @return 若为空 则传null
     */
    public static Integer strTransferToInteger(String numText) {
        return isEmpty(numText) ? null : Integer.valueOf(numText);
    }

    /**
     * 字符串处理
     *
     * @param str
     * @return 为空时返回NUll
     */
    public static String strTrim(String str) {
        return isEmpty(str) ? null : str.trim();
    }

    /**
     * 根据圆心、半径算出经纬度范围
     *
     * @param x
     *         圆心经度
     * @param y
     *         圆心纬度
     * @param r
     *         半径（米）
     * @return double[4] 南侧经度，北侧经度，西侧纬度，东侧纬度
     */
    public static double[] getLatLonRange(double lon, double lat, int r) {
        double DEF_PI = 3.14159265359; // PI
        double DEF_PI180 = 0.01745329252; // PI/180.0
        double DEF_R = 6370693.5; // radius of earth
        double[] range = new double[4];
        // 角度转换为弧度
        double ns = lat * DEF_PI180;
        double sinNs = Math.sin(ns);
        double cosNs = Math.cos(ns);
        double cosTmp = Math.cos(r / DEF_R);
        // 经度的差值
        double lonDif = Math.acos((cosTmp - sinNs * sinNs) / (cosNs * cosNs)) / DEF_PI180;
        // 保存经度
        range[0] = lon - lonDif;
        range[1] = lon + lonDif;
        double m = 0 - 2 * cosTmp * sinNs;
        double n = cosTmp * cosTmp - cosNs * cosNs;
        double o1 = (0 - m - Math.sqrt(m * m - 4 * (n))) / 2;
        double o2 = (0 - m + Math.sqrt(m * m - 4 * (n))) / 2;
        // 纬度
        double lat1 = 180 / DEF_PI * Math.asin(o1);
        double lat2 = 180 / DEF_PI * Math.asin(o2);
        // 保存
        range[2] = lat1;
        range[3] = lat2;
        return range;
    }

    public static void setTextViewLineExtra(final TextView textView, final float add,
                                            final float mult) {
        ViewTreeObserver vto = textView.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @SuppressWarnings("deprecation")
            @SuppressLint("NewApi")
            public void onGlobalLayout() {
                int textLine = textView.getLineCount();
                if (textLine > 0) {
                    if (android.os.Build.VERSION.SDK_INT >=
                            android.os.Build.VERSION_CODES.JELLY_BEAN) {
                        textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                    if (textLine > 1) {
                        textView.setLineSpacing(add, mult);
                        // textView.setIncludeFontPadding(false);
                    } else {
                        textView.setLineSpacing(0, 1);
                        // textView.setIncludeFontPadding(true);
                    }
                }

            }
        });
    }

    public static String myUUID() {
        StringBuilder sb = new StringBuilder();
        int start = 48, end = 58;
        appendChar(sb, start, end);
        appendChar(sb, 65, 90);
        appendChar(sb, 97, 123);
        String charSet = sb.toString();
        StringBuilder sb1 = new StringBuilder();
        for (int i = 0; i < 24; i++) {
            int len = charSet.length();
            int pos = new Random().nextInt(len);
            sb1.append(charSet.charAt(pos));
        }
        return sb1.toString();
    }

    public static void appendChar(StringBuilder sb, int start, int end) {
        int i;
        for (i = start; i < end; i++) {
            sb.append((char) i);
        }
    }

    /**
     * @param args
     * @return 将String[]中的字符串用空格串联起来
     */
    public static String getString(String[] args) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < args.length; i++) {
            sb.append(args[i]);
            if (i != args.length - 1) {
                sb.append("  ");
            }
        }
        return sb.toString();
    }

    // 获取屏幕宽度
    public static int getScreenWidthIntPx() {
        if (screenWidth <= 0) {
            setScreenSize();
        }
        return screenWidth;
    }

    public static int getScreenHeightIntPx() {
        if (screenHeight <= 0) {
            setScreenSize();
        }
        return screenHeight;
    }

    // 获取屏幕高度
    public static void setScreenSize() {
        android.view.WindowManager windowsManager =
                (android.view.WindowManager) LeDimApplication.getInstance()
                                                             .getSystemService(Context.WINDOW_SERVICE);
        android.view.Display display = windowsManager.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        display.getMetrics(dm);
        int mWidth = dm.widthPixels;
        int mHeight = dm.heightPixels;
        if (mHeight > mWidth) {// layout port
            // 竖屏 .......
            screenWidth = mWidth;
            screenHeight = mHeight;

        } else {// layout land
            // 横屏
            screenWidth = mHeight;
            screenHeight = mWidth;
        }
    }

    public static boolean isNeedUpdate(String currVer, String newVer) {
        String[] currentVer = currVer.split("\\.");
        String[] newestVer = newVer.split("\\.");
        for (int i = 0; i < currentVer.length; i++) {
            if (!TextUtils.isEmpty(currentVer[i]) && !TextUtils.isEmpty(newestVer[i])) {
                if (Integer.valueOf(newestVer[i]) > Integer.valueOf(currentVer[i])) {
                    return true;
                } else if (Integer.valueOf(currentVer[i]) > Integer.valueOf(newestVer[i])) {
                    return false;
                }
            }

        }

        return false;
    }

    /**
     * 给手机号加密
     *
     * @param num
     *         1300000000
     * @return 130****0000
     */
    public static String getSerectTeleNum(String phoneNum) {
        if (!TextUtils.isEmpty(phoneNum) && 11 == phoneNum.trim().length()) {
            return phoneNum.substring(0, 3) + "****" + phoneNum.substring(7, phoneNum.length());
        }
        return null;
    }

    /**
     * 替换字符串所有空格
     *
     * @param str
     * @return
     */
    public static String strTrimAll(String str) {
        if (!TextUtils.isEmpty(str)) {
            return str.replaceAll("\\s*", "");
        }
        return str;
    }

    // 验证邮箱的正则表达式
    public static boolean isEmail(String email) {
        String str = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    public static String formatRating(String rating) {
        BigDecimal num = new BigDecimal(rating);
        DecimalFormat fmt = new DecimalFormat("#############0.0");
        return fmt.format(num);
    }

    // 0- 99 随机数
    public static int randomNum() {
        Random rd = new Random();
        return 0 + rd.nextInt(99);
    }

    public static String mapArraysToString(HashMap<Integer, String>[] array) {
        StringBuffer sb = new StringBuffer();
        if (array != null && array.length > 0) {
            for (HashMap<Integer, String> s : array) {
                Iterator<Integer> iterator = s.keySet().iterator();
                while (iterator.hasNext()) {
                    sb.append(s.get(iterator.next())).append(" ");
                }
            }
        }
        return sb.toString();
    }

    /**
     * 秒转 xx小时xx分钟xx秒
     */
    public static String secToTime1(String sTime) {
        int time = Integer.valueOf(sTime);
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0) {
            return "不足1分钟";
        } else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                if (minute == 0) {
                    timeStr = "不足1分钟";
                } else {
                    if (second == 0) {
                        timeStr = minute + "分钟";
                    } else {
                        timeStr = minute + "分钟" + second + "秒";
                    }
                }

            } else {
                hour = minute / 60;
                if (hour > 99) {
                    return "99小时59分钟59秒";
                }
                minute = minute % 60;
                second = time - hour * 3600 - minute * 60;
                if (hour == 0) {
                    if (minute == 0) {
                        timeStr = "不足1分钟";
                    } else {
                        if (second == 0) {
                            timeStr = minute + "分钟";
                        } else {
                            timeStr = minute + "分钟" + second + "秒";
                        }

                    }
                } else {
                    if (minute == 0) {
                        if (second == 0) {
                            timeStr = hour + "小时";
                        } else {
                            timeStr = hour + "小时" + second + "秒";
                        }
                    } else {
                        if (second == 0) {
                            timeStr = hour + "小时" + minute + "分钟";
                        } else {
                            timeStr = hour + "小时" + minute + "分钟" + second + "秒";
                        }
                    }
                }
            }
        }
        return timeStr;
    }

    public static String unitFormat(int i) {
        String retStr = null;
        if (i >= 0 && i < 10) {
            retStr = "0" + Integer.toString(i);
        } else {
            retStr = "" + i;
        }
        return retStr;
    }

    /**
     * 秒转 xx:xx:xx
     */
    public static String secToTime(String sTime) {
        int time = Integer.valueOf(sTime);
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0) {
            return "";
        } else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                timeStr = unitFormat(minute) + ":" + unitFormat(second);
            } else {
                hour = minute / 60;
                if (hour > 99) {
                    return "99:59:59";
                }
                minute = minute % 60;
                second = time - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
            }
        }
        return timeStr;
    }
}
